package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	businessRes "github.com/flipped-aurora/gin-vue-admin/server/model/business/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
)

type EnterpriseApi struct {
}

var enterpriseService = service.ServiceGroupApp.BusinessServiceGroup.EnterpriseService

// CreateEnterprise 创建企业
// @Tags Enterprise
// @Summary 创建企业
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Enterprise true "创建企业"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /enterprise/createEnterprise [post]
func (enterpriseApi *EnterpriseApi) CreateEnterprise(c *gin.Context) {
	var enterprise business.Enterprise
	err := c.ShouldBindJSON(&enterprise)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		enterprise.UserId = userId
	}
	reenterprise, err := enterpriseService.GetEnterpriseByName(enterprise.UserId, enterprise.Name)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reenterprise.Name == enterprise.Name {
		response.FailWithMessage("该名称的数据已存在", c)
		return
	}
	if err := enterpriseService.CreateEnterprise(&enterprise); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteEnterprise 删除企业
// @Tags Enterprise
// @Summary 删除企业
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Enterprise true "删除企业"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /enterprise/deleteEnterprise [delete]
func (enterpriseApi *EnterpriseApi) DeleteEnterprise(c *gin.Context) {
	var enterprise business.Enterprise
	err := c.ShouldBindJSON(&enterprise)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		enterprise.UserId = userId
	}
	if err := enterpriseService.DeleteEnterprise(enterprise); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteEnterpriseByIds 批量删除企业
// @Tags Enterprise
// @Summary 批量删除企业
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除企业"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /enterprise/deleteEnterpriseByIds [delete]
func (enterpriseApi *EnterpriseApi) DeleteEnterpriseByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	var userIdInfo uint
	//当不是管理员时
	if isAdmin == 2 {
		userIdInfo = userId
	}
	if err := enterpriseService.DeleteEnterpriseByIds(IDS, userIdInfo); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateEnterprise 更新企业
// @Tags Enterprise
// @Summary 更新企业
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Enterprise true "更新企业"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /enterprise/updateEnterprise [put]
func (enterpriseApi *EnterpriseApi) UpdateEnterprise(c *gin.Context) {
	var enterpriseUpdate businessReq.EnterpriseUpdate
	err := c.ShouldBindJSON(&enterpriseUpdate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//赋值
	var enterprise business.Enterprise
	err = copier.Copy(&enterprise, &enterpriseUpdate)
	if err != nil {
		global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
		response.FailWithMessage("赋值时发生错误", c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//管理员判断
	if isAdmin == 2 {
		enterprise.UserId = userId
	}
	reenterprise, err := enterpriseService.GetEnterpriseByName(enterprise.UserId, enterprise.Name)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reenterprise.ID != enterprise.ID {
		response.FailWithMessage("该名称的数据已存在", c)
		return
	}
	if err := enterpriseService.UpdateEnterprise(enterprise); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindEnterprise 用id查询企业
// @Tags Enterprise
// @Summary 用id查询企业
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query business.Enterprise true "用id查询企业"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /enterprise/findEnterprise [get]
func (enterpriseApi *EnterpriseApi) FindEnterprise(c *gin.Context) {
	var enterprise business.Enterprise
	err := c.ShouldBindQuery(&enterprise)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//管理员判断
	if isAdmin == 2 {
		enterprise.UserId = userId
	}
	reenterprise, err := enterpriseService.GetEnterprise(enterprise.ID, enterprise.UserId)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reenterprise.ID == 0 {
		response.FailWithMessage("没有该数据", c)
		return
	}
	response.OkWithData(gin.H{"reenterprise": reenterprise}, c)

}

// GetEnterpriseList 分页获取企业列表
// @Tags Enterprise
// @Summary 分页获取企业列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.EnterpriseSearch true "分页获取企业列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /enterprise/getEnterpriseList [get]
func (enterpriseApi *EnterpriseApi) GetEnterpriseList(c *gin.Context) {
	var pageInfo businessReq.EnterpriseSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := utils.GetUserID(c)
	pageInfo.UserId = userId
	list, total, err := enterpriseService.GetEnterpriseInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	//赋值
	var enterpriseQueryList []businessRes.EnterpriseQuery
	err = copier.Copy(&enterpriseQueryList, &list)
	if err != nil {
		global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
		response.FailWithMessage("赋值时发生错误", c)
		return
	}

	//定义用户数组,分类数组

	var classifyIdList []uint
	for _, v := range enterpriseQueryList {
		classifyIdList = append(classifyIdList, v.ClassifyId)
	}

	if err != nil {
		global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
		response.FailWithMessage("获取用户信息失败", c)
		return
	}
	classifyList, err := classifyService.GetClassifyList(classifyIdList)
	if err != nil {
		global.GVA_LOG.Error("获取分类信息失败!", zap.Error(err))
		response.FailWithMessage("获取分类信息失败", c)
		return
	}
	//定义分类map
	classifyMap := make(map[uint]business.Classify)
	for k, _ := range classifyList {
		classifyMap[classifyList[k].ID] = classifyList[k]
	}
	for k, v := range enterpriseQueryList {
		enterpriseQueryList[k].Classify = classifyMap[v.ClassifyId]
	}
	response.OkWithDetailed(response.PageResult{
		List:     enterpriseQueryList,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// AdminGetEnterpriseList 管理员分页获取企业分类列表
// @Tags Enterprise
// @Summary 分页获取企业列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.EnterpriseSearch true "管理员分页获取企业分类列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /enterprise/adminGetEnterpriseList [get]
func (enterpriseApi *EnterpriseApi) AdminGetEnterpriseList(c *gin.Context) {
	var pageInfo businessReq.EnterpriseSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	if isAdmin == 1 {
		list, total, err := enterpriseService.GetEnterpriseInfoList(pageInfo)
		if err != nil {
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			response.FailWithMessage("获取失败", c)
		}
		//赋值
		var enterpriseAdminQueryList []businessRes.EnterpriseAdminQuery
		err = copier.Copy(&enterpriseAdminQueryList, &list)
		if err != nil {
			global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
			response.FailWithMessage("赋值时发生错误", c)
			return
		}

		//附带用户信息
		//定义用户数组,分类数组
		var userIdList []uint
		var classifyIdList []uint
		for _, v := range enterpriseAdminQueryList {
			userIdList = append(userIdList, v.UserId)
			classifyIdList = append(classifyIdList, v.ClassifyId)
		}
		userList, err := userService.FindUserByIdList(userIdList)
		if err != nil {
			global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
			response.FailWithMessage("获取用户信息失败", c)
			return
		}
		classifyList, err := classifyService.GetClassifyList(classifyIdList)
		if err != nil {
			global.GVA_LOG.Error("获取分类信息失败!", zap.Error(err))
			response.FailWithMessage("获取分类信息失败", c)
			return
		}
		//定义用户map
		userMap := make(map[uint]businessRes.UserInfo)
		for k, _ := range userList {
			userMap[userList[k].ID] = businessRes.UserInfo{
				ID:       userList[k].ID,
				NickName: userList[k].NickName,
				Username: userList[k].Username,
				Phone:    userList[k].Phone,
			}
		}
		//定义用户分类map
		classifyMap := make(map[uint]business.Classify)
		for k, _ := range classifyList {
			classifyMap[classifyList[k].ID] = classifyList[k]
		}
		for k, v := range enterpriseAdminQueryList {
			enterpriseAdminQueryList[k].UserInfo = userMap[v.UserId]
			enterpriseAdminQueryList[k].Classify = classifyMap[v.ClassifyId]
		}
		response.OkWithDetailed(response.PageResult{
			List:     enterpriseAdminQueryList,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	} else {
		response.FailWithMessage("你没有权限", c)
	}

}
